package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    //  private Map<String,Object> cache=new HashMap<>();

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
//        查出所有分类
        List<CategoryEntity> categoryEntities = super.baseMapper.selectList(null);
//        组装父子树形结构
//         找到所有一级分类
        List<CategoryEntity> level1Menu = categoryEntities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
//           使用递归方法 获取每个父节点下的子节点 作为children传入
            menu.setChildren(getChildrens(menu, categoryEntities));
            return menu;
        }).sorted((menu1, menu2) -> {
//          将数据按照Sort进行正序排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menu;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 检查当前要删除的菜单 是否被别处引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        System.out.println(catelogId + "ID数据");
        List<Long> paths = new ArrayList<>();

        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新操作
     *@CacheEvict 失效模式
     * @param category
     */
    // @CacheEvict(value = "category",key = "'getLevel1Categorys'")
/*    @Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category",key = "'getCatalogJson'")
    })*/
    @CacheEvict(value = "category",allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {

        this.updateById(category);
        categoryBrandRelationService.updateCategory(
                category.getCatId(),
                category.getName()
        );
    }

    // 需要指定到放到那个名字下的缓存
    @Cacheable(value = {"category"},key = "#root.method.name")  //当前方法返回值要缓存  缓存中有就不调用方法 没有就调用
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        long l = System.currentTimeMillis();

        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }


    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        System.out.println("数据库查询");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
//        1.查出所有分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
//       2. 封装数据
        Map<String, List<Catelog2Vo>> collect1 = level1Categorys.stream().collect(Collectors.toMap(
                k -> k.getCatId().toString(), v -> {
//      1.每一个的一级分类，查到这个一级分类的二级分类
                    List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
//                    2.封装上面的结果
                    List<Catelog2Vo> catelog2Vos = null;
                    if (categoryEntities != null) {
                        catelog2Vos = categoryEntities.stream().map(
                                l2 -> {
                                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());
//                                    找三级分类
                                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                                    if (level3Catelog != null) {
//                                        格式封装
                                        List<Catelog2Vo.Category3Vo> collect = level3Catelog.stream().map(l3 -> {
                                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString());
                                            return category3Vo;
                                        }).collect(Collectors.toList());
                                        catelog2Vo.setCatalog3List(collect);
                                    }
                                    return catelog2Vo;
                                }).collect(Collectors.toList());
                    }
                    return catelog2Vos;
                }
        ));
        return collect1;
    }

    //TODO 堆外内存溢出
   // @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        /*
         * 1.空结果缓存：解决缓存穿透
         * 2.设置过期时间（加随机值） ：解决缓存雪崩
         * 3.加锁：解决缓存击穿
         *
         * */
        // 1.加入缓存数据
        String catelogJSON = redisTemplate.opsForValue().get("catelogJSON");
        if (StringUtils.isEmpty(catelogJSON)) {
            System.out.println("缓存未命中，查询数据库");
            // 缓存中没有数据,去数据库查询
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();

            return catalogJsonFromDb;
        }
        System.out.println("缓存命中，返回数据");
        // 转换为指定类型
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });

        return result;
    }

    /**
     * 缓存数据如何保持一致
     *  1.双写模式  2.失效模式   会产生赃数据
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        // 1.设置锁
        RLock lock = redisson.getLock("CatalogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;
    }


    // redis分布式锁
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        // 1.抢占分布式锁，去redis占坑 设置过期时间与枷锁操作一致  防止 解锁失败
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("枷锁成功");
            // 枷锁成功 。。业务执行
            // 2.设置过期时间与枷锁操作一致 防止 解锁失败
            //redisTemplate.expire("lock",30,TimeUnit.MINUTES);
            Map<String, List<Catelog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            } finally {
                // 官方文档解锁操作 lua 脚本
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then  return redis.call('del', KEYS[1]) else return 0 end";
                // 使用redis的execute操作脚本 传入三个值 ：脚本内容及返回值类型 || 解锁的锁名 || 锁的value值
                Long integer = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);

            }

/*            // 解锁操作 获取当前锁的值
            String lockValue = redisTemplate.opsForValue().get("lock");
            // 获取锁值与uuid值是否相等 解锁自己的锁过期则不再解锁
            if(uuid.equals(lockValue)){
                redisTemplate.delete("lock");
            }*/
            return dataFromDb;
        } else {
            // 加锁失败 重试
            // 休眠
            System.out.println("枷锁失败");
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
            }
            return getCatalogJsonFromDbWithRedisLock();//自旋

        }


    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        // 得到锁后再去缓存中去确认，没有才继续查询
        String catelogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catelogJSON)) {
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });

            return result;
        }

        System.out.println("数据库数据被查询");
        /*
         * 1.将数据库多次查询变为一次
         * */
        List<CategoryEntity> selectList = baseMapper.selectList(null);
//        1.查出所有分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
//       2. 封装数据
        Map<String, List<Catelog2Vo>> collect1 = level1Categorys.stream().collect(Collectors.toMap(
                k -> k.getCatId().toString(), v -> {
//      1.每一个的一级分类，查到这个一级分类的二级分类
                    List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
//                    2.封装上面的结果
                    List<Catelog2Vo> catelog2Vos = null;
                    if (categoryEntities != null) {
                        catelog2Vos = categoryEntities.stream().map(
                                l2 -> {
                                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());
//                                    找三级分类
                                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                                    if (level3Catelog != null) {
//                                        格式封装
                                        List<Catelog2Vo.Category3Vo> collect = level3Catelog.stream().map(l3 -> {
                                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString());
                                            return category3Vo;
                                        }).collect(Collectors.toList());
                                        catelog2Vo.setCatalog3List(collect);
                                    }
                                    return catelog2Vo;
                                }).collect(Collectors.toList());
                    }
                    return catelog2Vos;
                }
        ));
        // 3.查到数据库再次放入缓存
        String s = JSON.toJSONString(collect1);
        redisTemplate.opsForValue().set("catelogJSON", s, 1, TimeUnit.DAYS);
        return collect1;
    }

    //从数据库查询数据
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithLocalLock() {
/*        Map<String, List<Catelog2Vo>> catalogJson = (Map<String, List<Catelog2Vo>>) cache.get("catalogJson");

        if(cache.get("catalogJson")==null){
            cache.put("catalogJson",collect1);
            return catalogJson;
        }*/
        /**
         * 只要是同一把锁，就能锁住这个锁的所有线程
         * 1. SpringBoot的所有组件都是单列的
         */
        //TODO 本地锁 锁不了全部,分布式锁锁住所有
        // 同步代码块
        synchronized (this) {
            // 得到锁后再去缓存中去确认，没有才继续查询
            return getDataFromDb();
        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());

        return collect;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    /*
     *  CategoryEntity: 父节点数据
     *  List<CategoryEntity>: 所有数据
     *   按照父子节点匹配格式化所有的子节点
     * */
    //    递归查询 子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }
}